import { del, get, put, post } from "@/request";
import { defineStore } from "pinia";
import { ref, reactive, Reactive } from "vue";

export interface Stucture {
  _id?: string;
  name?: string;
  code?: string;
  fuzename?: string;
  pid?: number;
  id?: number;
  p_id?: string;
  sortnum?: number;
}

export interface StuctureRes {
  data: Stucture[];
  total: number;
}

const stuctureVal: Stucture = {
  _id: undefined,
  name: "",
  code: "",
  fuzename: "",
  pid: 0,
  id: 0,
  p_id: "",
  sortnum: 0,
};

export const useStuctureStore = defineStore("orStucture", () => {
  const stuctures: Ref<Stucture[]> = ref<Stucture[]>([] as Stucture[]);
  const stucture: Reactive<Stucture> = reactive<Stucture>(stuctureVal);
  const stucture2: Reactive<Stucture> = reactive<Stucture>({} as Stucture);
  const id = ref(0);
  const buildTree = (data: Stucture[]): Stucture[] => {
    const map = new Map();
    console.log(map);
    
    const rootNodes: Stucture[] = [] as Stucture[];

    // 将数据转换成 Map，以便快速查找
    data.forEach((item) => {
      map.set(item.id, item);
    });

    // 遍历数据，构建树形结构
    data.forEach((item) => {
      const parentId = item.pid;
      console.log(parentId);
      
      if (parentId === 0) {
        // 如果没有父节点，则是根节点
        rootNodes.push(item);
      } else {
        // 如果有父节点，则查找父节点并将其添加到父节点的 children 数组中
        const parent = map.get(parentId);
        if (parent) {
          if (!parent.children) {
            parent.children = [];
          }
          parent.children.push(item);
        }
      }
    });

    return rootNodes;
  };
  const get_stucture = async () => {
    const data: StuctureRes = await get("/system/baseSet/stucture");
    stuctures.value = buildTree(data.data);
    id.value = data.total;
  };
  const add_stucture = async () => {
    stucture.id = id.value + 1;
    // 用于添加子节点
    if (stucture._id) {
      stucture.p_id = stucture._id;
    }
    console.log(stucture);

    await post("/system/baseSet/stucture/add", stucture);
    await get_stucture();
  };
  const del_stucture = async () => {
    console.log(stucture);

    await del("/system/baseSet/stucture/del", { _id: stucture._id });
    await get_stucture();
  };
  const edit_stucture = async () => {
    console.log(stucture);

    await put("/system/baseSet/stucture/update", stucture);
    await get_stucture();
  };
  const set_stucture = (item: Stucture) => {
    console.log(item);

    Object.assign(stucture, item);
    Object.assign(stucture2, item);
    console.log(stucture);
  };
  return {
    stuctures,
    stucture,
    get_stucture,
    add_stucture,
    edit_stucture,
    del_stucture,
    stucture2,
    set_stucture,
  };
});
